﻿using System;
using System.Collections.Generic;
using LoungeRepo.Contracts.Core;
using LoungeRepo.Contracts.Normalizer;
using LoungeRepo.Normalizer.DataStructures;

namespace LoungeRepo.Normalizer
{
    public class EntityNormalizer : IEntityNormalizer
    {
        private readonly EntityResolutionRequestDelegate resolveEntityReference;


        public EntityNormalizer(EntityResolutionRequestDelegate resolveEntityReference)
        {
            this.resolveEntityReference = resolveEntityReference;
        }


        public IEnumerable<INormalizedEntity> Normalize(object nonEntityObject, string id, string partition)
        {
            return Normalize(new WrapperEntity { Id = id, Partition = partition, NonEntityObject = nonEntityObject });
        }


        public IEnumerable<INormalizedEntity> Normalize(object entityObject)
        {
            if (entityObject is ILoungeRepoEntityIdentity)
                return new ObjectGraphNormalizer()
                            .NormalizeEntityGraph(entityObject);

            //TODO: check for entities not implementing ILoungeRepoEntityIdentity

            throw new ApplicationException("Invalid entity type! Must implement ILoungeRepoEntityIdentity");
        }


        public object Denormalize(INormalizedEntity normalizedEntity)
        {
            object entity = new ObjectGraphDenormalizer(this.resolveEntityReference)
                                    .Denormalize(normalizedEntity);

            if (entity is WrapperEntity)
                return (entity as WrapperEntity).NonEntityObject;

            return entity;
        }
    }
}
